<template>
  <view :class="theme" style="padding-bottom: 150rpx; padding-bottom: calc(env(safe-area-inset-bottom) + 150rpx);">
    <view @click.stop="checkedItem(index)" v-for="(item, index) in address" :key="index" class="bg-2 mt-10 p-30">
      <label class="fs-28">
        <text class="mr-20">{{ item.name }}</text>
        <text class="color-9">{{ item.mobile || "-" }}</text>
      </label>
      <view class="fd-row ai-center mt-16 pb-20" style="border-bottom: 2rpx solid #f5f5f5;">
        <text class="f1 fs-28 mr-20 multi-ellipsis" style="border-right: 2rpx solid #f5f5f5;">
          {{ item.remark }}
        </text>
      </view>

      <view class="fd-row ai-center jc-end mt-20">
        <button @click.stop="removeItem(index)" class="fs-24 color-9 border-none m-0" hover-class="tap-hover" plain>
          删除
        </button>
      </view>
    </view>

    <u-empty v-if="!address?.length" src="/static/img/blank.png" mode="address" marginTop="60" icon-size="400"
      color="#9b9b9b" />

    <view class="fixed bottom-0 jc-sb bg-2"
      style="padding-bottom: env(safe-area-inset-bottom); box-sizing: content-box; left: var(--window-left); right: var(--window-right);">
      <navigator url="/pages/client/main/setAddress" hover-class="tap-hover" style="margin: 30rpx; line-height: 88rpx;"
        class="bg-6 br-10 color-2 text-center fs-32">
        添加地址
      </navigator>
    </view>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import { useStore } from "vuex";

const { theme } = useMapState(["theme"]);
const address = ref<any[]>([]);
const store = useStore();

onShow(() => {
  uni.request({
    url: "/addressList",
    success({ data }: any) {
      address.value = data;
    }
  });
});

let enabledSelectAddress = false;
onLoad(({ enabled_select_address = 0 }: any) => {
  enabledSelectAddress = !!+enabled_select_address;
})

const checkedItem = (index: number) => {
  if (!enabledSelectAddress) return;
  store.commit("setState", { key: "address", value: address.value[index] });
  uni.navigateBack();
}

const removeItem = (index: number) => {
  uni.showModal({
    title: "温馨提示",
    content: "确定要删除该地址吗？",
    success({ confirm }) {
      const { id } = address.value[index]
      confirm && uni.request({
        url: "/delAddress",
        data: { id },
        success() {
          address.value.splice(index, 1);
          store.state.address.id === id &&
            store.commit("setState", { key: "address", value: {} })
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped></style>